<?php

namespace App\Console\Commands\Tools\Camera;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Shop\Enum\CameraCacheEnum;
use App\Kuafu\Shop\Enum\CodeEnum;
use App\Kuafu\Shop\Model\CameraModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Service\CameraLibrary\YlCamera;
use App\Kuafu\Shop\Service\ShopService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

class SyncYlCameraBind extends Command
{
    protected $signature   = 'tools:sync-yl-camera-bind {--shopCode=}';
    protected $description = '同步门店摄像头绑定关系';

    private array $resetShopList = [];

    public function handle()
    {
        $updateShopCode = $this->option('shopCode');

        $updateShopCode = explode(',', $updateShopCode);
        $updateShopCode = array_filter($updateShopCode);

        // 拉取影流所有的门店列表
        $camera = new YlCamera(null);

        $deviceListResult = $camera->getDeviceList();

        $deviceList = $deviceListResult['list'];

        foreach ($deviceList as $item) {
            // 校验最近注册 3 天内的的才重新刷新数据
            $registerTime = strtotime($item['createTime']);
//            if (time() - $registerTime > 86400 * 3) {
//                continue;
//            }

            if (empty($item['name'])) {
                continue;
            }

            // 拆分 name
            $explodeName = explode('-', $item['name']);
            $shopCode    = $explodeName[0] ?? '';
            if (!is_numeric($shopCode) || empty($shopCode)) {
                continue;
            }

            if (!empty($updateShopCode) && !in_array($shopCode, $updateShopCode)) {
                continue;
            }

            // 获取渠道下的所有设备列表
            $deviceChannel     = $camera->getDeviceChannelsList($item['deviceId']);
            $deviceChannelList = $deviceChannel['list'] ?? [];
            $shopInfo          = ShopService::getShopInfoByCode($shopCode);
            $insertList        = [];
            foreach ($deviceChannelList as $channelList) {
                // 过滤不符合的设备编号

                if (strlen($channelList['channelId']) < 10) {
                    continue;
                }

                if (strpos($channelList['name'], 'Channel') !== false) {
                    continue;
                }

                if (strpos($channelList['name'], '前端报警输入') !== false) {
                    continue;
                }

//                $type         = Str::contains($camera['alias'],
//                    ['客流']) ? CodeEnum::SHOP_CAMERA_TYPE_1 : CodeEnum::SHOP_CAMERA_TYPE_2;
                $insertList[] = [
                    'serialNo'     => $channelList['id'],
                    'productKey'   => $channelList['deviceId'],
                    'tripleType'   => 0,
                    'name'         => $channelList['name'],
                    'deviceName'   => $channelList['channelId'],
                    'deviceSecret' => '',
                    'mac'          => '',
                    'shopId'       => $shopInfo->id,
                    'supplier'     => CameraModel::SUPPLIER_YING_LIU,
                    'createdAt'    => time(),
                    'updatedAt'    => time(),
                    'type'         => CodeEnum::SHOP_CAMERA_TYPE_2
                ];

                Cache::forget(CameraCacheEnum::getCameraListCacheKey($shopInfo->id));
                ShopService::updateShopInfo(['id' => $shopInfo->id], ['cameraSupplier' => 3]);
            }

            // 重置门店下的所有摄像头信息
            // 判断是否已经重置过一次了
            if (!in_array($shopInfo->id, $this->resetShopList)) {
                CameraModel::query()
                           ->where('shopId', $shopInfo->id)
                           ->where('deviceType', CameraModel::DEVICE_TYPE_CAMERA)
                           ->update([
                               'isDeleted' => BaseModel::DELETE_YES
                           ]);
                $this->resetShopList[] = $shopInfo->id;
            }


            if (count($insertList) > 0) {
                CameraModel::query()->insert($insertList);
            }
        }
    }
}
